<template>
  <el-dialog v-model="showModel" title="商品选择器" width="1130px" top="10vh" @open="handleOpened" @closed="handleClosed">
    <div class="goods-select">
      <l-r-content-index>
        <template #side-content>
          <LeftTree ref="LeftTreeRef" :tree-data="treeData" :show-little-point="false" :disable-select="false"
            @getTreeNodeId="clickTreeNode" />
        </template>

        <div class="content">
          <search-bar>
            <template #normal>
              <el-form-item label="商品名称">
                <el-input v-model="form.name" clearable placeholder="请输入商品名称" />
              </el-form-item>
              <goods-supplier-filter url="/mall/admin/product/getStore"
                @change="({ selected }) => form.storeId = selected" />
              <div class="area-input-box">
                <el-form-item label="积分区间" class="area-input">
                  <div class="input-box">
                    <el-input type="number" v-model.number="form.prePrice" placeholder="请输入积分下限"></el-input>
                    <div style="margin: 0 10px">
                      ~
                    </div>
                    <el-input type="number" v-model.number="form.aftPrice" placeholder="请输入积分上限"></el-input>
                  </div>

                </el-form-item>
                <el-form-item label="金额区间" class="area-input">
                  <div class="input-box">
                    <el-input type="number" v-model.number="form.preCashPrice" placeholder="请输入金额下限"
                      style="flex: 1;"></el-input>
                    <div style="margin: 0 10px">
                      ~
                    </div>
                    <el-input type="number" v-model.number="form.aftCashPrice" placeholder="请输入金额上限"
                      style="flex: 1;"></el-input>
                  </div>
                </el-form-item>
              </div>
            </template>
          </search-bar>
          <div class="statics">已选择<span class="checkColor">{{ selectedCards.size || 0 }}</span>个商品</div>

          <div v-loading="loading" class="list">
            <div v-for="item in list" :key="item.id" class="card" :class="{
              'card-selected': selectedCards.has(item.id)
            }" @click="clickCard(item)">
              <div class="img-wrapper">
                <img class="img" :src="item.thumbnailUrl">
              </div>
              <div class="text">
                <div class="line name">
                  {{ item.name }}
                </div>
                <div class="line price">
                  <!--                  {{item.showMinCurrencyPrice}}积分 + {{item.showMinPrice ? item.showMinPrice / 100 : item.showMinPrice}}元-->
                  {{ item.priceRange }}
                </div>
                <div class="line stock">
                  剩余库存：{{ item.stock }}
                </div>
              </div>
            </div>
          </div>

          <div class="pager">
            <el-pagination v-model:current-page="page.currentPage" :page-sizes="page.pageSizes" background
              layout="total, sizes, prev, pager, next, jumper" :page-size="page.showCount" :total="total"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </l-r-content-index>

      <!--      <div class="selected-area" v-if="selectedCards.size > 0">-->
      <!--        <div class="selected-item">-->
      <!--          当前选中项({{ selectedCards.size }}):-->
      <!--        </div>-->
      <!--        <div class="selected-item" v-for="[id, item] in selectedCards">-->
      <!--          <img class="selected-img" :src="item.thumbnailUrl"/>-->
      <!--          {{item.name}}-->
      <!--          <el-icon class="close-icon" @click="deleteSelected(id)"><Close /></el-icon>-->
      <!--          <span style="margin: 0 5px">|</span>-->
      <!--        </div>-->
      <!--      </div>-->
    </div>

    <template #footer>
      <el-dropdown v-if="multiSelect" class="cus-select" split-button @command="clickOtherBtn" @click="checkCurrent">
        全选本页商品
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="clearCurrent">
              清空本页已选
            </el-dropdown-item>
            <el-dropdown-item command="clearAll">
              清空全部已选
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button @click="showModel = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleConfirm">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { Ref, WritableComputedRef } from "vue";
import moment from "moment";
import { debounce } from "@/utils";
import { useGetGoodsCategory } from "@/views/pointsMall/compositions/useGetGoodsCategory";
import { getMallGoodsPage2 } from "@/api/pointsMall";
import { IGoodsPageRow } from "@/api/modules/pointsMall";


type ISelectItem = Pick<IGoodsPageRow, "id">

interface ISearchForm {
  mallId: number;
}

const props = withDefaults(defineProps<{
  show: boolean;
  values: ISelectItem[];
  searchForm: ISearchForm;
  withProducts?: boolean;
  multiSelect?: boolean;
}>(), {
  withProducts: false,
  multiSelect: false,
})

const emits = defineEmits<{
  (e: "update:show", value: boolean): void;
  (e: "click", value: any): void;
  (e: "confirm", value: ISelectItem[]): void;
}>()

const { goodsCateList, getGoodsCate } = useGetGoodsCategory()
// const { mallConfig } = useMallConfig()

const showModel: WritableComputedRef<boolean> = computed({
  get() {
    return props.show;
  },
  set(newValue) {
    emits("update:show", newValue)
  }
})

const treeData: Ref<any[]> = ref([] as any)
const getCate = async () => {
  await getGoodsCate(props.searchForm.mallId);
  treeData.value = [
    {
      id: "",
      name: "全部",
      children: [],
    },
  ].concat(goodsCateList.value);
};

const page = reactive({
  currentPage: 1,
  showCount: 10,
  pageSizes: [10, 20, 40],
})
const total: Ref<number> = ref(0);

const form = reactive({
  mallId: undefined,
  onlineStatus: 1,
  withProducts: false,
  name: "",
  storeId: null,
  categoryId: null,
  aftCashPrice: null,
  preCashPrice: null,
  prePrice: null,
  aftPrice: null,
})
const list: Ref<IGoodsPageRow[]> = ref([])
const loading = ref(true)
const getList = async () => {
  loading.value = true
  const rs = await getMallGoodsPage2({
    ...form,
    ...page,
    ...props.searchForm,
    // withProducts: props.withProducts
  })

  if (rs.code === 200) {
    list.value = rs.payload ?? []
    total.value = rs.page?.totalResult ?? 0;
  }
  loading.value = false
}

const debouncedSearch = debounce(() => {
  page.currentPage = 1;
  getList()
}, 700, false)

watch(() => form, debouncedSearch, {
  deep: true
})

watch(() => page, () => {
  getList();
}, {
  deep: true
})

const clickTreeNode = (node: any, data: any) => {
  form.categoryId = node.id;
}

const selectedCards: Ref<Map<number, ISelectItem>> = ref(new Map());
const clickCard = (item: IGoodsPageRow) => {
  // 单选
  if (!props.multiSelect) {
    selectedCards.value.clear();
    selectedCards.value.set(item.id, item);
  } else {
    // 多选
    if (selectedCards.value.has(item.id)) {
      selectedCards.value.delete(item.id);
    } else {
      selectedCards.value.set(item.id, item);
    }
  }
}

const clickOtherBtn = (command: string) => {
  //清除本页
  if (command == 'clearCurrent') {
    clearCurrent()
  }
  //清除全选
  if (command == 'clearAll') {
    clearSelected()
  }
}

//全选当前页
const checkCurrent = () => {
  list.value.forEach(i => {
    selectedCards.value.set(i.id, i)
  })
}
//清除本页已选
const clearCurrent = () => {
  list.value.forEach(i => {
    if (selectedCards.value.has(i.id)) {
      deleteSelected(i.id)
    }
  })
}
const deleteSelected = (id: number) => {
  selectedCards.value.delete(id);
}

const clearSelected = () => {
  selectedCards.value.clear();
}

const formatTime = (value: number) => {
  return value ? moment(value).format("YYYY.MM.DD") : ""
}

const handleConfirm = () => {
  showModel.value = false;
  emits("confirm", [...selectedCards.value.values()])
}

const echoSelected = () => {
  props.values.forEach(item => {
    selectedCards.value.set(item.id, item)
  })
}

const handleOpened = () => {
  getCate();
  getList();
  echoSelected();
}

const handleClosed = () => {
  selectedCards.value.clear();
}

const handleSizeChange = (val) => {
  page.showCount = val

}

const handleCurrentChange = (current) => {
  page.currentPage = current;

}
</script>

<style scoped lang="scss">
.goods-select {
  :deep(.lr-content) {
    .side-panel {
      height: 400px;
      min-height: unset;
      overflow: auto;
    }

    .main-panel {
      padding-left: 24px;

      .content {
        overflow-y: auto;
        max-height: 80vh;
        display: flex;
        flex-direction: column;
      }
    }
  }
}

.list {
  margin-top: 12px;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: flex-start;
  flex-wrap: wrap;

  .card {
    cursor: pointer;
    box-sizing: border-box;
    border: solid 1px transparent;
  }

  .card-active {
    background: var(--el-color-primary-light-9);
  }

  .card:hover {
    border: dashed 1px var(--el-color-primary);
  }

  .card-selected {
    background: #EEE;
  }
}

.card {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 140px;
  margin-right: 25px;
  margin-bottom: 10px;
  font-size: 12px;
  padding: 10px;
  border-radius: 5px;
  overflow: hidden;

  .img-wrapper {
    width: 120px;
    height: 80px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #F0f0f0;
    margin-bottom: 10px;
    padding: 5px;
    box-sizing: border-box;

    .img {
      max-width: 120px;
      max-height: 80px;
    }
  }

  .text {
    .line {
      margin-bottom: 5px;
    }

    .name {
      width: 120px;
      word-break: keep-all;
      white-space: nowrap;
      font-size: 14px;
      font-weight: bold;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 5px;
    }

    .price {
      color: var(--el-color-primary);
    }
  }
}

//.card:hover {
//  background: #EEE;
//}

.selected-area {
  overflow: hidden;
  margin: 10px 0 0 0;

  .selected-item {
    float: left;
    display: inline-flex;
    align-items: center;
    margin-right: 10px;

    .selected-img {
      max-width: 15px;
      max-height: 15px;
      margin-right: 10px;
    }

    .close-icon {
      cursor: pointer;
      color: var(--el-color-primary);
    }
  }
}

.checkColor {
  font-weight: 700;
  color: var(--el-color-primary);
}

.area-input-box {
  width: 100%;
  display: flex;
}

.area-input {
  width: 50%;

  .input-box {
    width: 100%;
    display: flex;

    :deep(.el-input) {
      flex: 1;

      .el-input__wrapper {
        .el-input__inner {
          width: 100%;
        }
      }

    }
  }
}

.cus-select {
  margin-right: 12px;

  :deep(.el-button) {
    color: var(--el-button-hover-text-color);
    border-color: var(--el-button-hover-border-color);
    background-color: var(--el-button-hover-bg-color);
    outline: none;

    &:hover {
      color: var(--el-color-white);
      background-color: var(--el-color-primary);
      border-color: var(--el-color-primary);
    }
  }

  :deep(.el-dropdown__caret-button) {
    color: var(--el-button-hover-text-color);
    border-color: var(--el-button-hover-border-color);
    background-color: var(--el-button-hover-bg-color);
    margin-left: -4px;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
</style>
